package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.RoleMapper;
import com.indusfo.spc.mapper.RoleMenuMapper;
import com.indusfo.spc.mapper.RoleStationMapper;
import com.indusfo.spc.mapper.RoleUserMapper;
import com.indusfo.spc.pojo.Role;
import com.indusfo.spc.pojo.RoleMenu;
import com.indusfo.spc.pojo.RoleStation;
import com.indusfo.spc.pojo.RoleUser;
import com.indusfo.spc.service.BaseService;
import com.indusfo.spc.service.RoleService;
import com.indusfo.spc.vo.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 角色定义表业务层
 *
 * @author 贺闻博
 * <p>
 * 2018年11月28日
 */
@Slf4j
@Service
public class RoleServiceImpl implements RoleService {

  private static final Logger logger = LoggerFactory.getLogger(RoleServiceImpl.class);
  @Resource
  private RoleMapper roleMapper;

  @Resource
  private RoleUserMapper roleUserMapper;

  @Resource
  private RoleStationMapper roleStationMapper;

  @Resource
  private RoleMenuMapper roleMenuMapper;
  @Resource
  private  BaseService baseService;

  /**
   * 查询所有角色功能
   */
  @Override
  public JSONObject selectRoleS(Role role) {
    List<Role> listRole = null;
    try {
      Integer pageSize = role.getPagesize();
      Integer pageIndex = role.getPageindex();
      if (pageSize != null && pageIndex != null) {
        role.setIncept(pageSize * (pageIndex - 1));
      }
      Integer roleId = role.getRoleId();
      if (roleId == null) {
        listRole = roleMapper.selectRoles(role);
      } else {
        listRole = roleMapper.selectRole(roleId);
      }
      int count = roleMapper.getCounts(role);
      return JSONObject.oK("查询成功", listRole, count);
    } catch (GlobalException e) {
      logger.error(e.getMessage(), e);
      return JSONObject.build(500, e.getMessage());
    }
  }

  /**
   * 新增角色信息
   */
  @Override
  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public JSONObject insertRole(Role role) throws Exception {
      checkParams(role);
      List<String> menuCodeList = role.getMenuCodeList();
      List<Integer> userIdList = role.getUserIdList();
      List<String> staIdList = role.getStaIdList();
      /*
      新增角色信息
        */
      roleMapper.insertRole(role);

      Integer roleId = role.getRoleId();
      /*
      2. 新增菜单权限集合
      */
    List<RoleMenu> roleMenus = new ArrayList<>();
      if(!menuCodeList.isEmpty()){
        for(String menuCode : menuCodeList){
          if(menuCode.length() == 2 || menuCode.length() == 4|| menuCode.length() == 6){
              RoleMenu roleMenu = new RoleMenu();
              roleMenu.setRoleId(roleId);
              roleMenu.setMenuCode(menuCode);
              roleMenus.add(roleMenu);
          }else{
            throw new Exception("菜单编码不规范,一级目录2位编码，二级目录4位编码，三级目录6位编码");
          }
        }
      }
      /*
      3. 新增用户权限集合
      */
      List<RoleUser> roleUsers = new ArrayList<>();
      if(!userIdList.isEmpty()){
        for(Integer userId : userIdList){
          RoleUser roleUser = new RoleUser();
          roleUser.setRoleId(roleId);
          roleUser.setUserId(userId);
          roleUsers.add(roleUser);
        }
      }
       /*
      4. 新增作业限集合
      */
       List<RoleStation> roleStations = new ArrayList<>();
       if(!staIdList.isEmpty()){
         for(String stationId : staIdList){
           if(stationId.endsWith("S")){
             RoleStation roleStation = new RoleStation();
             roleStation.setStationId(Integer.parseInt(stationId.substring(0, stationId.length() - 1)));
             roleStation.setRoleId(roleId);
             roleStations.add(roleStation);
           }
         }
       }
   if(!roleUsers.isEmpty()){
     roleUserMapper.insertListRoleUser(roleUsers);
   }
    if(!roleMenus.isEmpty()){
      roleMenuMapper.insertListRoleMenu(roleMenus);
    }
    if(!roleStations.isEmpty()){
      roleStationMapper.insertListRoleStation(roleStations);
    }
    return JSONObject.build(JSONObject.SUCCESS, "新增数据成功", roleId);

  }

  /**
   * 更新角色信息
   */
  @Override
  public JSONObject updateRole(Role role) throws Exception {
    checkParams(role);
    List<String> menuCodeList = role.getMenuCodeList();
    List<Integer> userIdList = role.getUserIdList();
    List<String> staIdList = role.getStaIdList();
     /*
      1.更改角色信息
    */
    roleMapper.updateRole(role);
    Integer roleId = role.getRoleId();
    /*
    查询数据库已授权的菜单编码
      */
    List<String> oldMenuCodeList = roleMenuMapper.selectMenuCodeByRoleId(roleId);
    /*
    新增到数据库的菜单编码《差集》
      */
    List<String> addMenuCodeList = menuCodeList.stream().filter(num -> !oldMenuCodeList.contains(num)).collect(Collectors.toList());
     /*
    删除数据库的菜单编码《差集》
      */
    List<String> delMenuCodeList = oldMenuCodeList.stream().filter(num -> !menuCodeList.contains(num)).collect(Collectors.toList());
     /*
      2. 新增菜单权限集合
      */
    List<RoleMenu> roleMenus = new ArrayList<>();
    if(!addMenuCodeList.isEmpty()){
      for(String menuCode : addMenuCodeList){
        if(menuCode.length() == 2 || menuCode.length() == 4 || menuCode.length() == 6){
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuCode(menuCode);
            roleMenus.add(roleMenu);
        }else{
          throw new Exception("菜单编码不规范,一级目录2位编码，二级目录4位编码，三级目录6位编码");
        }
      }
    }

    /*
    查询数据库已授权的角色id
      */
    List<Integer> oldUserIdList = roleUserMapper.selectUserIdByRoleId(roleId);
     /*
    新增到数据库的用户id《差集》
      */
    List<Integer> addUserIdList =  userIdList.stream().filter(num -> !oldUserIdList.contains(num)).collect(Collectors.toList());
     /*
      删除数据库的用户id《差集》
      */
    List<Integer> delUserIdList = oldUserIdList.stream().filter(num -> !userIdList.contains(num)).collect(Collectors.toList());

    /*
      3. 新增用户权限集合
      */
    List<RoleUser> roleUsers = new ArrayList<>();
    if(!addUserIdList.isEmpty()){
      for(Integer userId : addUserIdList){
        RoleUser roleUser = new RoleUser();
        roleUser.setRoleId(roleId);
        roleUser.setUserId(userId);
        roleUsers.add(roleUser);
      }
    }

    /*
    查询数据库已授权的工位id
      */
    List<Integer> oldStationIdList = roleStationMapper.selectStationIdByRoleId(roleId);
    List<Integer> newStationIdList = new ArrayList<>();

      /*
      获取前台的数据并解析出工位id的集合
      */
    if(!staIdList.isEmpty()){
      for(String stationIdStr : staIdList){
        if(stationIdStr.endsWith("S")){
          int stationId = Integer.parseInt(stationIdStr.substring(0, stationIdStr.length() - 1));
          newStationIdList.add(stationId);
        }
      }
    }
     /*
    新增到数据库的工位id《差集》
      */
    List<Integer> addStationIdList = newStationIdList.stream().filter(num -> !oldStationIdList.contains(num)).collect(Collectors.toList());
     /*
    删除数据库的工位id《差集》
      */
    List<Integer> delStationIdList =  oldStationIdList.stream().filter(num -> !newStationIdList.contains(num)).collect(Collectors.toList());
     /*
      4. 新增作业限集合
      */
    List<RoleStation> roleStations = new ArrayList<>();
    if(!addStationIdList.isEmpty()){
      for(Integer stationId : addStationIdList){
          RoleStation roleStation = new RoleStation();
          roleStation.setStationId(stationId);
          roleStation.setRoleId(roleId);
          roleStations.add(roleStation);
      }
    }
    if(!roleUsers.isEmpty()){
      roleUserMapper.insertListRoleUser(roleUsers);
    }
    if(!delUserIdList.isEmpty()){
      roleUserMapper.deleteByUserIds(delUserIdList,roleId);
    }
    if(!roleMenus.isEmpty()){
      roleMenuMapper.insertListRoleMenu(roleMenus);
    }
    if(!delMenuCodeList.isEmpty()){
      roleMenuMapper.deleteByMenuCode(delMenuCodeList,roleId);
    }
    if(!roleStations.isEmpty()){
      roleStationMapper.insertListRoleStation(roleStations);
    }
    if(!delStationIdList.isEmpty()){
      roleStationMapper.deleteByStationId(delStationIdList,roleId);
    }
    return JSONObject.build(JSONObject.SUCCESS, "编辑成功", roleId);
  }

  @Override
  public String deleteRole(Integer[] roleIds, Integer dataState) {
    try {
      if (null == roleIds) {
        throw new ParamsErrorException("请选择要删除的角色");
      }
      if ("1".equals(roleIds)) {
        throw new ModifyFailedException("超级用户不能被删除");
      }
      if (dataState == null) {
        throw new ModifyFailedException("数据状态不能为空");
      }
      int num = roleMapper.deleteRole(roleIds, dataState);

      baseService.cascadeDeleteRole(roleIds, dataState);
      String msg = "";
      if (num == 0) {
        switch (dataState) {
          case 1:
            throw new ModifyFailedException("启用失败");
          case 2:
            throw new ModifyFailedException("删除失败");
          case 3:
            throw new ModifyFailedException("停用失败");
        }
      } else {
        switch (dataState) {
          case 1:
            msg = "启用成功";
            break;
          case 2:
            msg = "删除成功";
            break;
          case 3:
            msg = "停用成功";
            break;
        }
      }

      // ------------------------------------ 其他表操作begin -------------------------------------- //
      if (dataState == 2) {
        /*
        // 删除其他权限表关联数据，逻辑删除
        roleRightService.deleteRoleRightByRoleId(roleIds, dataState);
        associtionService.deleteAssociTionByRoleId(roleIds, dataState);
        roleUserService.deleteRoleUserByRoleId(roleIds, dataState);
        */
      }

      // ------------------------------------ 其他表操作end -------------------------------------- //
      return msg;

    } catch (GlobalException e) {
      logger.error(e.getMessage(), e);
      return e.getMessage();
    }
  }


  /**
   * 参数校验
   *
   * @param role
   * @return void
   * @author xuz
   * @date 2019/7/9 3:09 PM
   */
  private void checkParams(Role role) {
    if (role.getRoleId() != null) {
      if (role.getRoleId() == 1) {
        throw new ModifyFailedException("超级用户不能被编辑");
      }
    }
    if (role.getRoleName() == null) {
      throw new ModifyFailedException("角色名称不能为空");
    }

    int counts = roleMapper.getRepeatCounts(role);
    if (counts > 0) {
      throw new ParamsErrorException("该角色名已存在，请不要重复添加");
    }
  }

}
